package com.park.microprofile.configsourceprovider;

import org.eclipse.microprofile.config.spi.ConfigSource;
import org.eclipse.microprofile.config.spi.ConfigSourceProvider;

import java.util.*;

/**
 * 默认的配置源提供者
 *
 * @author Aaron
 * @date 2021/7/13 10:08
 */
public class DefaultConfigSourceProvider implements ConfigSourceProvider {
    /**
     * 配置源集合
     */
    private final List<ConfigSource> configSourceList = new LinkedList<>();

    public Iterable<ConfigSource> getConfigSources() {
        return getConfigSources(null);
    }

    @Override
    public Iterable<ConfigSource> getConfigSources(ClassLoader classLoader) {
        if (classLoader == null) {
            classLoader = Thread.currentThread().getClass().getClassLoader();
        }

        // 通过 SPI 机制获取 配置源
        ServiceLoader<ConfigSource> configSources = ServiceLoader.load(ConfigSource.class, classLoader);
        for (ConfigSource configSource : configSources) {
            configSourceList.add(configSource);
        }
        // 排序
        configSourceList.sort((o1, o2) -> o2.getOrdinal() - o1.getOrdinal());
        return Collections.unmodifiableList(configSourceList);
    }


}
